package cn.com.haopy.dataes.db.service.main.impl;

import cn.com.haopy.dataes.db.entity.main.HDSystem;
import cn.com.haopy.dataes.db.mapper.main.HDSystemMapper;
import cn.com.haopy.dataes.db.service.main.HDSystemService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class HDSystemServiceImpl extends ServiceImpl<HDSystemMapper, HDSystem> implements HDSystemService {
    @Override
    public Map<String, String> queryAll() {
        LambdaQueryWrapper<HDSystem> queryWrapper = new LambdaQueryWrapper<>();

        return getSystemConfigMap(queryWrapper);
    }

    private Map<String, String> getSystemConfigMap(LambdaQueryWrapper<HDSystem> queryWrapper) {
        List<HDSystem> systemList = super.list(queryWrapper);
        Map<String, String> data = new HashMap<>();
        for (HDSystem system : systemList) {
            data.put(system.getKeyName(), system.getKeyValue());
        }
        return data;
    }

    @Override
    public void updateConfig(Map<String, String> data) {
        for (Map.Entry<String, String> entry : data.entrySet()) {
            LambdaQueryWrapper<HDSystem> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(HDSystem::getDeleted, false).eq(HDSystem::getKeyName, entry.getKey());

            HDSystem system = new HDSystem();
            system.setKeyName(entry.getKey());
            system.setKeyValue(entry.getValue());
            system.setUpdateTime(LocalDateTime.now());

            super.saveOrUpdate(system, queryWrapper);
        }
    }

    @Override
    public boolean addConfig(String key, String value) {
        HDSystem system = new HDSystem();
        system.setKeyName(key);
        system.setKeyValue(value);
        system.setCreateTime(LocalDateTime.now());
        system.setUpdateTime(LocalDateTime.now());
        return super.save(system);
    }
}
